package com.qu.waibao.baidu;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.location.Address;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiDetailSearchOption;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.qu.waibao.R;
import com.qu.waibao.base.BaseActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class MapActivity extends BaseActivity implements View.OnClickListener,
        LocationUtils.ILocateDelegate, OnGetGeoCoderResultListener,OnGetPoiSearchResultListener {
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.iv_publish)
    ImageView iv_publish;
    @BindView(R.id.tv_sure)
    TextView tv_sure;
    @BindView(R.id.mMapView)
    MapView mMapView;
    @BindView(R.id.et_search)
    EditText et_search;
    private BaiduMap mBaiduMap;
    private GeoCoder mGeoSearch; //地理编码
    private PoiSearch mPoiSearch; //周边检索
    private LatLng location;  //当前定位经纬度
    private String keywords = "";
    private String address = "";
    @Override
    protected int getContentView() {
        return R.layout.activity_map;
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        tv_title.setText("设置位置");
        iv_publish.setVisibility(View.GONE);
        tv_sure.setVisibility(View.VISIBLE);
        tv_sure.setText("确定");
        LocationUtils.locateDelegateArrayList.add(this);
        initMap();
        et_search.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode==KeyEvent.KEYCODE_ENTER && event.getAction()==KeyEvent.ACTION_UP){
                    keywords = et_search.getText().toString();
                    if (!TextUtils.isEmpty(keywords)) {
                        startSearch(keywords);
                    }
                    return true;
                }
                return false;
            }
        });
        if(LocationUtils.Mylocation != null){
            et_search.setText(LocationUtils.addressbean.address);
            location = new LatLng(LocationUtils.longitude, LocationUtils.latitude);
            address = LocationUtils.addressbean.district+LocationUtils.addressbean.street+LocationUtils.addressbean.streetNumber;
        }
    }

    private void initMap() {
        // 初始化搜索模块，注册事件监听
        mGeoSearch = GeoCoder.newInstance();
        mGeoSearch.setOnGetGeoCodeResultListener(this);

        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        // 地图初始化
        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();
        startGeocode();
        // 开启定位图层
        MapStatusUpdate center = MapStatusUpdateFactory
                .newLatLng(new LatLng(LocationUtils.longitude, LocationUtils.latitude));
        mBaiduMap.animateMapStatus(center);
        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                MapStatusUpdate center = MapStatusUpdateFactory.newLatLng(latLng);
                mBaiduMap.animateMapStatus(center);
            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                return false;
            }
        });

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

            }

            @Override
            public void onMapStatusChange(MapStatus mapStatus) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus mapStatus) {
                startReverseGeoCode(mapStatus.target);
            }
        });

        MapStatusUpdate zoom = MapStatusUpdateFactory.zoomTo(15.0f);
        mBaiduMap.animateMapStatus(zoom);
    }

    @Override
    protected void initData() {
        super.initData();
    }
    @Override
    public void onPause() {
        super.onPause();
        mMapView.onPause();
        LocationUtils.locateDelegateArrayList.remove(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        mMapView.onResume();
    }
    @OnClick({R.id.tv_search,R.id.ll_back,R.id.tv_sure})
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_search:
                keywords = et_search.getText().toString().trim();
                if(LocationUtils.Mylocation != null) {
                    startSearch(keywords);
                }
                break;
            case R.id.ll_back:
                onBackPressed();
                break;
            case R.id.tv_sure:
                Intent intents = new Intent();
                intents.putExtra("address",address);
                intents.putExtra("longitude",location.longitude);
                intents.putExtra("latitude",location.latitude);
                setResult(RESULT_OK,intents);
                finish();
                break;
        }
    }

    @Override
    public void onLocateSuccess(BDLocation location) {
        // 开启定位图层
        MapStatusUpdate center = MapStatusUpdateFactory
                .newLatLng(new LatLng(location.getLongitude(), location.getLatitude()));
        mBaiduMap.animateMapStatus(center);
    }

    @Override
    public void onLocateFailed() {

    }

    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {

        location = result.getLocation();
        MapStatusUpdate center = MapStatusUpdateFactory.newLatLng(location);
        mBaiduMap.animateMapStatus(center, 1);
    }

    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
        ReverseGeoCodeResult.AddressComponent addressDetail = reverseGeoCodeResult.getAddressDetail();
        StringBuilder builder = new StringBuilder();
        String addresss = builder.append(addressDetail.province).append(addressDetail.city).append(addressDetail.district)
        .append(addressDetail.street).append(addressDetail.streetNumber).toString();
        et_search.setText(addresss);

        address =  addressDetail.street+addressDetail.streetNumber;
        Log.e("TAG","address---"+address);
        location = reverseGeoCodeResult.getLocation();
    }

    //根据经纬度来查找
    public void startReverseGeoCode(LatLng ptCenter){
        // 反Geo搜索
        mGeoSearch.reverseGeoCode(new ReverseGeoCodeOption()
                .location(ptCenter));
    }
    public void startGeocode(){
        if(LocationUtils.Mylocation != null) {
            mGeoSearch.geocode(
                    new GeoCodeOption()
                            .city(LocationUtils.addressbean.city)
                            .address(LocationUtils.addressbean.address));
        }else {
            LocationUtils.startLocation();
        }
    }
    public void startSearch(String keywords){

        if(LocationUtils.Mylocation != null) {
            mPoiSearch.searchInCity(
                    new PoiCitySearchOption()
                    .city(LocationUtils.addressbean.city)
                    .keyword(keywords));
        }else {
            LocationUtils.startLocation();
        }

    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        intent.putExtra("address",address);
        intent.putExtra("longitude",location.longitude);
        intent.putExtra("latitude",location.latitude);
        setResult(RESULT_OK,intent);
        super.onBackPressed();
    }

    @Override
    public void onGetPoiResult(PoiResult poiResult) {
        location = poiResult.getAllPoi().get(0).location;
        MapStatusUpdate center = MapStatusUpdateFactory.newLatLng(location);
        mBaiduMap.animateMapStatus(center, 1);

    }

    @Override
    public void onGetPoiDetailResult(PoiDetailResult poiDetailResult) {

    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }
}
